package dhome.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Host {
	final static boolean isWindows = System.getProperty("os.name")
			.toLowerCase().startsWith("win");

	static {
		if (System.getProperty("DS_HOME") == null)
			System.setProperty("DS_HOME", System.getProperty("user.dir"));

		addLibraryPath(System.getProperty("TTOOL_HOME") + File.separator
				+ "native" + File.separator + get_classfier());
	}

	public final static String HOME = System.getProperty("DS_HOME");
	protected static Logger log = LoggerFactory.getLogger(Host.class);
	private static String classfier;

	protected static Runtime run = Runtime.getRuntime();
	private static Charset _charset = Charset.defaultCharset();

	public static void addLibraryPath(String path) {
		if (System.getProperty("java.library.path") != null)
			path = path + File.pathSeparator
					+ System.getProperty("java.library.path");

		System.setProperty("java.library.path", path);

		// set sys_paths to null so that java.library.path will be reevalueted
		// next time it is needed
		try {
			final Field sysPathsField = ClassLoader.class
					.getDeclaredField("sys_paths");
			sysPathsField.setAccessible(true);
			sysPathsField.set(null, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String get_classfier() {
		if (classfier == null) {
			String os = System.getProperty("os.name").split(" ")[0];
			classfier = (os + "_" + System.getProperty("os.arch"))
					.toLowerCase();
		}
		return classfier;
	}

	/**
	 * 获得系统变量的值 Usage： getSystemInfo("hostname") getSystemInfo("ip")
	 * 返回LocalHost网卡ip地址.
	 * 
	 * @param type
	 *            the type
	 * @return the system info
	 */
	public static String getSystemInfo(String type) {
		try {
			if (System.getProperty(type) != null)
				return System.getProperty(type);
			if (type.equalsIgnoreCase("ip")) {
				InetAddress i = InetAddress.getLocalHost();
				if (i.getHostName() != null && i.getHostName().length() > 0)
					return i.getHostName();
				return i.getHostAddress();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 执行一个命令，返回原始结果. 不会处理switchTo函数的传入目录
	 * 
	 * @param cmd
	 *            the cmd
	 * @return the string
	 */
	public static String exec0(String cmd) {
		String line = "";
		try {
			Process pro = run.exec(new String[] { "sh", "-c", cmd });
			BufferedReader bri = new BufferedReader(new InputStreamReader(
					pro.getInputStream(), _charset));

			String tmp = null;
			while ((tmp = bri.readLine()) != null) {
				line += tmp.trim() + "\n";
			}
			bri.close();
			pro.waitFor();

			if (line == null || line.trim().length() == 0)
				System.out.println("exec no return " + cmd);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return line;
	}

	/**
	 * 执行 && 返回 不会处理switchTo函数的传入目录
	 * 
	 * @param cmd
	 */
	public static void exec0_wait(String cmd) {
		try {
			Process pro = run.exec(new String[] { "sh", "-c", cmd });
			final Process fpro = pro;
			new Thread() {
				@Override
				public void run() {
					try {
						fpro.waitFor();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// public String execToString(String command) {
	// CommandLine commandline = CommandLine.parse(command);
	//
	// try {
	// exec.execute(commandline);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return(outputStream.toString());
	// }

	/**
	 * 执行 && 等待结果 不会处理switchTo函数的传入目录
	 * 
	 * @param cmd
	 */
	public void exec0_without_return(String cmd) {
		try {
			Process pro = run.exec(cmd);
			pro.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * host的字符集，默认为charset
	 * 
	 * @param charset
	 * @see Expect#charset
	 */
	public static void set_charset(String charset) {
		_charset = Charset.forName(charset);
	}
}
